package com.hymjweb.demo.hymj.customer_manage.service;

import com.hymjweb.demo.SpringAopUtil;
import com.hymjweb.demo.framework.cache.service.GlobalCacheService;
import com.hymjweb.demo.framework.result.MIniUIGridResultMap;
import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.sys.SysConstant;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.hymj.customer_manage.bean.BCustomerBean;
import com.hymjweb.demo.hymj.customer_manage.bean.BCustomerPojo;
import com.hymjweb.demo.hymj.customer_manage.contact.bean.BCustomerContactPojo;
import com.hymjweb.demo.hymj.customer_manage.contact.service.BCustomerContactService;
import com.hymjweb.demo.hymj.customer_manage.invoice.bean.BCustomerInvoicePojo;
import com.hymjweb.demo.hymj.customer_manage.invoice.service.BCustomerInvoiceService;
import com.hymjweb.demo.hymj.customer_manage.mapper.BCustomerMapper;
import com.hymjweb.demo.hymj.log_manage.aop.annotation.OperationLogger;
import com.hymjweb.demo.hymj.system_maintenance.user.bean.XtUserPojo;
import com.hymjweb.demo.hymj.system_maintenance.user.service.XtUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class BCustomerService extends BaseService {
    @Autowired
    private BCustomerMapper bCustomerMapper;

    @Autowired
    private BCustomerContactService bCustomerContactService;

    @Autowired
    private BCustomerInvoiceService bCustomerInvoiceService;

    @Autowired
    private GlobalCacheService globalCacheService;

    @Autowired
    private XtUserService xtUserService;

    public Object getPageList(Map map) {
        this.pageListInit(map);
        List list = bCustomerMapper.findAll(map);
        MIniUIGridResultMap resultMap = this.pageToGrid(list);
        return resultMap;
    }

    @Transactional(rollbackFor = {Exception.class})
    public int insert(BCustomerBean bean) throws Exception {
        if (bean == null) {
            throwException("客户添加参数错误!");
        }

        BCustomerPojo bCustomerPojo = bean.getCustomerPojo();
        bCustomerPojo.setId(getSysStrId());
        Date currentDate = this.getSysTime();
        String czyId = this.getLoginCzyId();
        bCustomerPojo.setCreateTime(currentDate);
        bCustomerPojo.setCreateUserId(czyId);
        bCustomerPojo.setUpdateTime(currentDate);
        bCustomerPojo.setUpdateUserId(czyId);

        BCustomerPojo bCustomerPojoOld = bCustomerMapper.findUK(bCustomerPojo.getName(), null);
        if (bCustomerPojoOld != null) {
            throw new Exception(SysConstant.XT_DIC_ERROR_MSG.have_uk_b_customer.getName());
        }

        // 客户联系人
        List<BCustomerContactPojo> contactPojoList = bean.getContactPojoList();

        // 客户发票信息
        List<BCustomerInvoicePojo> invoicePojoList = bean.getInvoicePojoList();

        // 调用代码进行插入
        int affectRows = SpringAopUtil.getBean(this.getClass()).insert(bCustomerPojo);

        if (affectRows <= SysConstant.INT_ZERO) {
            return SysConstant.INT_ZERO;
        }

        if (contactPojoList != null && !contactPojoList.isEmpty()) {
            // 添加时，直接批量插入
            for (BCustomerContactPojo pojo : contactPojoList) {
                pojo.setId(this.getSysStrId());
                pojo.setCustomerId(bCustomerPojo.getId());
                pojo.setCreateTime(currentDate);
                pojo.setCreateUserId(czyId);
                pojo.setUpdateTime(currentDate);
                pojo.setUpdateUserId(czyId);
            }

            bCustomerContactService.batchInsert(contactPojoList);
        }

        if (invoicePojoList != null && !invoicePojoList.isEmpty()) {
            for (BCustomerInvoicePojo pojo : invoicePojoList) {
                pojo.setId(this.getSysStrId());
                pojo.setCustomerId(bCustomerPojo.getId());
            }

            bCustomerInvoiceService.batchInsert(invoicePojoList);
        }

        return affectRows;
    }

    //@OperationLogger(oper = SysConstant.OPER_ADD, operTitle = "客户管理-添加", operMemo = "", classType = BCustomerPojo.class)
    @Transactional(rollbackFor = {Exception.class})
    public int saveInsert(BCustomerPojo pojo) throws Exception {
        if(pojo==null){
            throwException("客户添加参数错误!");
        }
        return bCustomerMapper.insert(pojo);
    }

    @OperationLogger(oper = SysConstant.OPER_UPDATE, operTitle = "客户管理-更新", operMemo = "", classType = BCustomerPojo.class)
    @Transactional(rollbackFor = {Exception.class})
    public int saveUpdate(BCustomerPojo pojo) throws Exception {
        if(pojo==null){
            throwException("客户更新参数错误!");
        }
        return bCustomerMapper.update(pojo);
    }

    @Transactional(rollbackFor = {Exception.class})
    public int insert(BCustomerPojo pojo) throws Exception {
        if (pojo == null) {
            throwException("客户添加参数错误");
        }
        checkPojo(pojo);
        pojo.setCreateTime(this.getSysTime());
        pojo.setCreateUserId(this.getLoginCzyId());
        pojo.setUpdateTime(this.getSysTime());
        pojo.setUpdateUserId(this.getLoginCzyId());
        int flag = SpringAopUtil.getBean(this.getClass()).saveInsert(pojo);
        if (flag > SysConstant.INT_ZERO) {
            globalCacheService.loadBCustomerCache();
        }
        return flag;
    }


    @Transactional(rollbackFor = {Exception.class})
    public int update(BCustomerBean bean) throws Exception {
        if (bean == null) {
            throwException("客户更新参数错误!");
        }

        Date currentDate = this.getSysTime();
        String czyId = this.getLoginCzyId();

        BCustomerPojo bCustomerPojo = bean.getCustomerPojo();
        bCustomerPojo.setUpdateTime(currentDate);
        bCustomerPojo.setUpdateUserId(czyId);

        String customerId = bCustomerPojo.getId();

        int affectRows = SpringAopUtil.getBean(this.getClass()).saveUpdate(bCustomerPojo);

        if (affectRows <= SysConstant.INT_ZERO) {
            return SysConstant.INT_ZERO;
        }

        // 这两个列表是要分两种处理方式，有id 与无 id,有 id 采用更新，无 id 采用插入，需要注意的是，原来在外面被删除的要直接删除
        List<BCustomerContactPojo> contactPojoList = bean.getContactPojoList();
        if (contactPojoList != null && !contactPojoList.isEmpty()) {
            for (BCustomerContactPojo pojo : contactPojoList) {
                if (pojo.getId() == null || DataTypeUtil.isEmptyStr(pojo.getId())) {
                    pojo.setId(this.getSysStrId());
                }
                pojo.setCustomerId(customerId);
            }
            int affectRows1 = bCustomerContactService.batchUpdate(contactPojoList, customerId);
        }

        List<BCustomerInvoicePojo> invoicePojoList = bean.getInvoicePojoList();
        if (invoicePojoList != null && !invoicePojoList.isEmpty()) {
            for (BCustomerInvoicePojo pojo : invoicePojoList) {
                if (pojo.getId() == null || DataTypeUtil.isEmptyStr(pojo.getId())) {
                    pojo.setId(this.getSysStrId());
                }
                pojo.setCustomerId(customerId);
            }

            int affectRows2 = bCustomerInvoiceService.batchUpdate(invoicePojoList, customerId);
        }

        // 更新缓存
        globalCacheService.loadBCustomerCache();

        return affectRows;
    }

    /**
     * 检查必输项
     *
     * @param pojo
     */
    private void checkPojo(BCustomerPojo pojo) throws Exception {
        DataTypeUtil.isEmptyStrThenThrow(pojo.getId(), SysConstant.XT_DIC_ERROR_MSG.no_id.getName());
        DataTypeUtil.isEmptyStrThenThrow(pojo.getName(), SysConstant.XT_DIC_ERROR_MSG.no_name.getName());
    }

    @OperationLogger(oper = SysConstant.OPER_DELETE, operTitle = "客户管理-删除", operMemo = "", classType = BCustomerPojo.class)
    @Transactional(rollbackFor = {Exception.class})
    public int delete(String id) throws Exception {
        if (DataTypeUtil.isEmptyStr(id)) {
            throwException("客户删除参数错误!");
        }
        List<BCustomerContactPojo> bCustomerContactPojoList = bCustomerContactService.findByBCustomerId(id);
        if (bCustomerContactPojoList != null && !bCustomerContactPojoList.isEmpty()) {
            throwException("待删除客户下有客户联系人，该客户不能删除!");
        }
        int flag = bCustomerMapper.delete(id);
        if (flag > SysConstant.INT_ZERO) {
            globalCacheService.loadBCustomerCache();
        }
        return flag;
    }

    public BCustomerBean queryById(String id) throws Exception {
        DataTypeUtil.isEmptyStrThenThrow(id, "客户查询参数错误!");
        BCustomerBean bean = new BCustomerBean();
        BCustomerPojo pojo = bCustomerMapper.queryById(id);
        List<BCustomerContactPojo> pojoList = bCustomerContactService.findByBCustomerId(id);
        bean.setCustomerPojo(pojo);
        bean.setContactPojoList(pojoList);
        return bean;
    }

    /**
     * 根据查询条件查询客户
     *
     * @param queryKey
     * @return
     */
    public List<BCustomerPojo> queryDeliveryCustomerByKey(String queryKey) {
        return bCustomerMapper.queryDeliveryCustomerByKey(queryKey);
    }


    public List<BCustomerPojo> findCacheAll(Map map) {
        return bCustomerMapper.findCacheAll(map);
    }

    public List<XtUserPojo> queryDeliveryCustomerSalesmanByKey(String key) {
        return xtUserService.queryCustomerSalesmanByKey(key);
    }
}
